
var db = {

    // 获取数据
    set: function(name, val) {

        if (typeof val == 'object')
            val = JSON.stringify(val);
        else if (typeof val != 'string')
            val = val + '';
            
    },

    // 写入数据
    get: function(name) {
        return name;
    },

    // 创建数据库
    createDateBase: function(name, fun) {

        db.set(name, {
            createDateBase: new Date().getTime()
        });

        if (fun) fun();
    },

    // 创建表 [val 初始化数据]
    createTable: function(datebase, table, data:any, fun) {
        // name dbname.tablename

        var selfDate = db.get(datebase);

        if (selfDate) {

            var jsonDateBase = JSON.parse(selfDate);

            if (data) {
                if (typeof data == 'object') {
                    if (data.push) {
                        for (var i = 0; i < data.length; i++) 
                        {
                            data[i].index = i;
                        }
                        jsonDateBase[table] = data;
                    } else {
                        data.index = 0;
                        jsonDateBase[table] = [data];
                    }
                } else if (typeof data == 'string') {
                    var d = [data];
                    jsonDateBase[table] = d;
                }
            } else {
                jsonDateBase[table] = [];
            }

            db.set(datebase, jsonDateBase);

            if (fun) {
                fun();
            }

        } else {
            db.createDateBase(datebase, function() {
                db.createTable(datebase, table, data, fun);
            });
        }

    },

    // 重新塑造WHERE
    newWhere: function(where, header) {
        
        console.log(where)

        var whereArr = where.split(' ');

        for (var i = 0; i < whereArr.length; i++) {

            switch ((i + 4) % 4) {
                case 0:
                    whereArr[i] = header + whereArr[i];
                    break;
                case 2:
                    whereArr[i] = '"' + whereArr[i] + '"';
                    break;
                default:
                    break;
            }

        }

        where = '';

        for (var i = 0; i < whereArr.length; i++) {

            var thisWherethisr = whereArr[i];

            if (i != 0 || i != whereArr.length - 1) {
                switch (whereArr[i]) {
                    case 'is':
                    case '=':
                        where += '== ';
                        break;

                    case 'and':
                        where += '&& ';
                        break;

                    case 'or':
                        where += '|| ';
                        break;

                    default:
                        where += thisWherethisr + ' ';
                        break;
                }
            } else {
                where += thisWherethisr + ' ';
            }

        }

        return where;
    },

    // 数组排序
    // orderby [row desc || row asc]
    arrSoct: function(result, orderby) {

        var orderByParam = orderby.split(' '),
            key = orderByParam[0];

        for (var j = 1, jl = result.length; j < jl; j++) {

            var temp = result[j],
                val = temp[key],
                i = j - 1;

            while (i >= 0 && result[i][key] > val) {
                result[i + 1] = result[i];
                i = i - 1;
            }

            result[i + 1] = temp;

        }

        if (orderByParam[1] && orderByParam[1] == 'desc') {
            return result.reverse();
        }

        return result;

    },

    // 数组分组
    arrGroup: function(result, row) {

        var arr = [],
            isArr = [];

        for (var i = 0; i < result.length; i++) {

            if (!result[i]) return;

            var rowVal = eval('result[i].' + row);

            for (var j = 0; j < result.length; j++) {

                try {

                    if (eval('rowVal == result[j].' + row)) isArr.push(eval('result[i].' + row));

                } catch (e) {

                }

            }

            if (isArr.length > 0) {
                arr.push({
                    count: isArr.length,
                    date: isArr[0]
                });
                isArr = [];
                i--
            }

            for (var j = 0; j < result.length; j++) {

                if (eval('rowVal == result[j].' + row)) {
                    result.splice(j, 1);
                    j--
                }

            }

        }

        return arr;
    }

};

class store {

    datebase: string;
    table: string;
    length: number;
    date: any;

    constructor(context) {

        var dateBaseParam = context.split('.');

        if (dateBaseParam.length > 1) {
            this.datebase = '_a_b_c_d_' + dateBaseParam[0];
            this.table = dateBaseParam[1];
        } else {
            this.datebase = '_a_b_c_d_';
            this.table = dateBaseParam[0];
        }


    }


    // 加入用户标识
    user(val: any) {
        if (val) {
            this.datebase = this.datebase + val;
        }
        return this;
    }

    // 加入关键字
    key(val: any) {
        if (val) {
            this.datebase = this.datebase + '_' + val;
        }
        return this;
    }

    // 选择器
    eq(val: any) {
        if (val >= 0) {
            return this.date[val];
        } else {
            return null;
        }
    }

    initData(data) {
        var self = this;
        db.createTable(self.datebase, self.table, data, function () { });
    }

    // 插入数据
    insert(val) {

        var self = this;

        var selfDate = db.get(self.datebase);

        if (selfDate) {

            var jsonDateBase = JSON.parse(selfDate);

            if (val) {

                if (jsonDateBase && jsonDateBase[self.table]) {

                    //						console.log('insert', typeof val)
                    if (typeof val == 'object') {

                        // 数组循环插入
                        if (val.push) {

                            for (var n = 0; n < val.length; n++) {
                                val[n].index = jsonDateBase[self.table].length;
                                jsonDateBase[self.table].push(val[n]);
                            }

                        } else {

                            val.index = jsonDateBase[self.table].length;
                            jsonDateBase[self.table].push(val);

                        }

                    } else if (typeof val == 'string') {

                        jsonDateBase[self.table].push(val);

                    }

                    self.date = jsonDateBase;

                    self.length = self.date.length;

                    db.set(self.datebase, jsonDateBase);

                } else {
                    //						console.log('insert createTable')

                    db.createTable(self.datebase, self.table, false, function () {
                        self.insert(val);
                    });

                }

            }

        } else {

            //				console.log('insert createDateBase')
            // datebase null

            db.createDateBase(self.datebase, function () {
                self.insert(val);
            });

        }

        return this;

    }

    update(data, where) {

        this.length = 0;

        var selfDate = db.get(this.datebase);

        if (selfDate) {

            var jsonDateBase = JSON.parse(selfDate);

            if (jsonDateBase[this.table]) {

                var tableDate = jsonDateBase[this.table];

                if (where) {
                    where = db.newWhere(where, "tableDate[n].");
                } else {
                    return alert('条件不可未空');
                }

                for (var n = 0; n < tableDate.length; n++) {

                    try {

                        var accord = eval(where);

                        //							console.log(accord, where)

                        if (accord) {

                            for (var name in data) {

                                var row = name,
                                    val = data[name];

                                if (typeof val == 'object')
                                    eval("tableDate[n]." + row + " = val");
                                else
                                    eval("tableDate[n]." + row + " = '" + val + "'");

                            };

                            this.length++;

                        }

                    } catch (e) {
                        //TODO handle the exception
                    }

                }

                this.date = jsonDateBase;

                db.set(this.datebase, jsonDateBase);
            }

        }

        return this;
    }

    delete(where) {

        this.length = 0;

        var selfDate = db.get(this.datebase);

        if (selfDate) {

            var jsonDateBase = JSON.parse(selfDate);

            if (jsonDateBase[this.table]) {

                var tableDate = jsonDateBase[this.table];

                if (where) {
                    where = db.newWhere(where, "tableDate[n].");
                } else {
                    return alert('条件不可未空');
                }

                for (var n = 0; n < tableDate.length; n++) {

                    try {

                        var accord = eval(where);

                        if (accord) {
                            tableDate.splice(n, 1);
                            n--
                            this.length++;
                        }

                    } catch (e) {
                        //TODO handle the exception
                    }

                }

                this.date = jsonDateBase;

                db.set(this.datebase, jsonDateBase);
            }

        }

        return this;
    }

    select(where) {

        var ret = [];

        var selfDate = db.get(this.datebase);

        if (selfDate) {

            var jsonDateBase = JSON.parse(selfDate);

            if (jsonDateBase[this.table]) {

                var tableDate = jsonDateBase[this.table];

                if (where) {
                    where = db.newWhere(where, 'tableDate[n].');

                    for (var n = 0; n < tableDate.length; n++) {

                        try {

                            console.log(where)

                            var accord = eval(where);

                            if (accord) {
                                ret.push(tableDate[n]);
                            }
                        } catch (e) {
                            //TODO handle the exception
                        }

                    }
                } else {
                    ret = tableDate;
                }
            }

        }

        this.date = ret;

        this.length = ret.length;

        return this;
    }

    orderby(val) {

        this.date = db.arrSoct(this.date, val);

        this.length = this.date.length;

        return this;
    }

    groupby(val) {

        this.date = db.arrGroup(this.date, val);

        this.length = this.date.length;

        return this;
    }

}